import * as fs from 'fs-extra';
import * as path from 'path';

import { CustomHelpers } from 'joi';
import { DriverService } from '$domain/model/driver';

import { logger, isPositiveInteger, untildify } from '$common';

export const simModelValidator = (localModelDir: string, helpers: CustomHelpers) => {

  if (!fs.pathExistsSync(localModelDir)) {
    throw new Error(`LocalModelDir: '${localModelDir}' is not exist.`);
  }
  return localModelDir;
};

export const productValidator = (product: string, helpers: CustomHelpers) => {

  const supportedProducts = DriverService.getDriverNames();
  
  if (!supportedProducts.includes(product)) {
    throw new Error(`Unsupported product: ${product}, allowed: ${supportedProducts.join(',')}`);
  }
  return product;
};

export const timeoutValidator = (timeout: number, helpers: CustomHelpers) => {
  
  if (timeout === 0) { return null; }

  if (!isPositiveInteger(timeout)) {
    throw new Error(`timeout: ${timeout} is not a positive integer.`);
  }
  return timeout;
};

export const specifiedLocalPathValidator = (specifiedLocalPath: string, helpers: CustomHelpers) => {
  if (!specifiedLocalPath) { return; }

  const parsedLocalPath = untildify(specifiedLocalPath);

  logger.debug(`🔄 try to convert tilde path(${specifiedLocalPath}) to an absolute path(${parsedLocalPath})`);

  if (!path.isAbsolute(parsedLocalPath)) {
    throw new Error(`specifiedLocalPath: ${specifiedLocalPath} must be tilde path or absolute path.`);
  }

  try {
    fs.ensureDirSync(parsedLocalPath);
  } catch (e) {
    throw new Error(`ensure directory failed: ${specifiedLocalPath}`);
  }
  return parsedLocalPath;
};